﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WpfAppDemo.Model;

namespace WpfAppDemo.DAL
{
    public class LocalDb
    {
        private List<Student> students;

        public LocalDb()
        {
            init();
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        private void init()
        {
            students = new List<Student>();
            for (int i = 0; i < 30; i++)
            {
                students.Add(new Student()
                {
                    Id = i,
                    Name = string.Format("学生{0}", i),
                    Age = new Random(i).Next(0, 100),
                    Classes = i % 2 == 0 ? "一班" : "二班"
                });
            }
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <returns></returns>
        public List<Student> Query()
        {
            return students;
        }

        /// <summary>
        /// 按名字查询
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public List<Student> QueryByName(string name)
        {
            return students.Where((t) => t.Name.Contains(name)).ToList();//FindAll((t) => t.Name.Contains(name));
        }

        public Student QueryById(int Id)
        {
            var student = students.FirstOrDefault((t) => t.Id == Id);
            if (student != null)
            {
                return new Student()
                {
                    Id = student.Id,
                    Name = student.Name,
                    Age = student.Age,
                    Classes = student.Classes
                };
            }
            return null;
        }


        /// <summary>
        /// 新增学生
        /// </summary>
        /// <param name="student"></param>
        public void AddStudent(Student student)
        {
            if (student != null)
            {
                students.Add(student);
            }
        }

        /// <summary>
        /// 删除学生
        /// </summary>
        /// <param name="Id"></param>
        public void DelStudent(int Id)
        {
            var student = students.FirstOrDefault((t) => t.Id == Id); //students.Find((t) => t.Id == Id);
            if (student != null)
            {
                students.Remove(student);
            }

        }
    }
}
